package dataStructure.tree.huffmanTree;

import java.util.ArrayList;
import java.util.Collections;

/**
 * @author lhn
 * @date 2024-09-05 15:20
 */

public class HuffmanTreeDemo {
    public static void main(String[] args) {
        int arr[] = {13, 7, 8, 3, 29, 6, 1};
        Node root = createHuffmanTree(arr);
        preOrder(root);
        //前序 67 29 38 15 7 8 23 10 4 1 3 6 13
    }

    public static Node createHuffmanTree(int[] arr) {
        ArrayList<Node> nodes = new ArrayList<>();
        // 先遍历arr，将每一个元素构成一个Node
        for (int value: arr
             ) {
            nodes.add(new Node(value));
        }

        while (nodes.size() > 1) {
            //1.排序
            Collections.sort(nodes);
//        System.out.println(nodes);
            //[Node [value=1], Node [value=3], Node [value=6], Node [value=7], Node [value=8], Node [value=13], Node [value=29]]

            //2.取出最小的两个二叉树，作为左右子树
            Node left = nodes.get(0);
            Node right = nodes.get(1);
            Node parent = new Node(left.getValue() + right.getValue());
            parent.setLeft(left);
            parent.setRight(right);
            nodes.remove(left);
            nodes.remove(right);
            nodes.add(parent);

            System.out.println(nodes);  //新添加的在末尾
        }
        return nodes.get(0);
    }

    public static void preOrder(Node root) {
        if (root != null) {
            root.preOrder();
        } else {
            System.out.println("空树");
        }
    }
}

// 创建结点
//让Node对象持续排序Collection集合排序，实现Comparable接口
class Node implements Comparable<Node>{
    private int value;
    private Node left;
    private Node right;
    public Node(int value) {
        this.value = value;
    }
    public int getValue() {
        return value;
    }
    public void setValue(int value) {
        this.value = value;
    }
    public Node getLeft() {
        return left;
    }
    public void setLeft(Node left) {
        this.left = left;
    }
    public Node getRight(){
        return right;
    }

    public void setRight(Node right) {
        this.right = right;
    }
    @Override
    public String toString() {
        return "Node [value=" + value + "]";
    }

    @Override
    public int compareTo(Node o) {
        // 从小到大排序
        //当前对象应该排在参数对象之前，则返回一个小于0的整数。
        //两个对象相等（即它们之间没有排序差异），则返回0。
        //当前对象应该排在参数对象之后，则返回一个大于0的整数。
        return this.value - o.value;
    }

    public void preOrder() {
        System.out.print(this.getValue() + " ");
        if (this.left != null) {
            this.left.preOrder();
        }
        if (this.right != null) {
            this.right.preOrder();
        }
    }
}